<!-- 商品详情页 -->
<template>
	<div class="product-detail-container">
		<HeadNav></HeadNav>

		<div v-if="loading" class="loading">
			<el-skeleton :rows="6" animated />
		</div>

		<div v-else-if="product" class="product-content">
			<!-- 商品图片 -->
			<div class="product-images">
				<img :src="getImageUrl(product.image)" :alt="product.name">
			</div>

			<!-- 商品信息 -->
			<div class="product-info">
				<h1 class="product-name">{{ product.name }}</h1>
				<p class="product-price">
				    ¥{{ combinationPrice ? (combinationPrice * quantity).toFixed(2) : product.price.toFixed(2) }}
				</p>

				<!-- 其他商品详情 -->
				<p>优惠： 6期免息，购买得积分</p>
				<p>保障： 极速退款，七天⽆理由退换</p>
				<p>配送： 多仓发货</p>
				<!-- 商品属性 -->
				<div class="product-config">
					<!-- 机身颜色 -->
					<div class="config-section">
						<label class="section-title">机身颜色</label>
						<div v-for="color in availableColors" :key="color.colorId" class="config-item"
							:class="{ active: selectedColor === color.colorId }"
							@click="handleSelect('color', color.colorId)">
							<span class="config-text">{{ color.colorName }}</span>
						</div>
					</div>

					<!-- 存储容量 -->
					<div class="config-section">
						<label class="section-title">存储容量</label>
						<div v-for="storage in availableStorages" :key="storage.capacityId" class="config-item"
							:class="{ active: selectedStorage === storage.capacityId }" 
							@click="handleSelect('storage', storage.capacityId)">
							<span class="config-text">{{ storage.capacityValue }}</span>
						</div>
					</div>

					<!-- 套餐类型 -->
					<div class="config-section">
						<label class="section-title">套餐类型</label>
						<div v-for="(packageType, index) in packageTypeList" :key="index" class="config-item"
							:class="{ active: selectedPackage === packageType }"
							@click="handleSelect('package', packageType)">
							<span class="config-text">{{ packageType }}</span>
						</div>
					</div>
				</div>
				<!-- 数量 -->
				<div class="inventory-container">
					<div class="quantity-section">
						<span>数量：</span>
						<!-- 减号按钮 -->
						<button class="quantity-btn" @click="decreaseQuantity">-</button>
						<!-- 数量显示 -->
						<span class="quantity-text">{{ quantity }}</span>
						<!-- 加号按钮 -->
						<button class="quantity-btn" @click="increaseQuantity">+</button>
					</div>
					<div class="stock-status" v-if="!inStock">
						<span>无货</span>
					</div>
				</div>
				 <div v-if="showAddSuccess" class="add-success-message">
				    <i class="el-icon-success"></i>
				    <span>商品已成功加入购物车！</span>
				  </div>
				<div class="carboxbutton">
				<div class="buyingoods" @click="incar()">加入购物车</div>
				<div class="buygoods" @click="buy()">立即购买</div>
				</div>
				
			</div>

		</div>

		<div v-else class="not-found">
			<el-empty description="商品未找到"></el-empty>
		</div>
	</div>
</template>

<script>
	import HeadNav from '../components/HeadNav.vue'
	import request from '@/utils/request.js'
	

	export default {
		name: 'ProductDetail',
		components: {
			HeadNav
		},

		data() {
			return {
				packageTypeList: ['官方标配'], // 可扩展其他套餐
				// 选中状态
				selectedColor: '',
				selectedStorage: '',
				selectedPackage: '官方标配',
				
				product: null,
				productIds:null,
				loading: false, //加载状态
				error: null,
				productConfigs: [], //配置信息
				availableColors: [], // 可用的颜色选项
				availableStorages: [], // 可用的存储选项
				quantity: 1, // 初始数量，可根据实际调整
				inStock: true ,// 假设初始有货
				currentCombination: null, // 存储当前选择的完整组合信息
				combinationPrice: null,
				combinationId: null,
				showAddSuccess: false // 新增：加入购物车成功提示状态
			}
		},
		// 首先加载
		created() {
			const productId = this.$route.params.product_id // 从路由参数获取

			if (productId) {
				this.fetchProductDetail(productId)
			} else {
				this.error = '缺少商品ID'
			}
		},
		methods: {
			getImageUrl(relativePath) {
				return require(`@/assets/img/goods/${relativePath}`)
			},
			// 获取商品信息
			fetchProductDetail(productId) {
				this.loading = true;
				// 1. 先请求商品详情
				request.get(`/products/${productId}`)
					.then(productRes => {
						if (productRes.code === '200') {
							this.product = productRes.data;
							this.productIds = productRes.data.product_id;
						} else {
							this.$message.error(productRes.msg || '获取商品详情失败');
						}

						// 2. 商品详情请求成功后，再请求商品配置
						return request.get(`/product-config/${productId}`);
					})
					.then(configRes => {
						if (configRes.code === '200') {
							this.productConfigs = configRes.data;
							// 从配置中提取颜色和容量选项
							this.processConfigData();
						} else {
							this.$message.error(configRes.msg || '获取商品配置失败');
						}
					})
					.catch(error => {
						console.error('请求商品信息失败:', error);
						this.$message.error('请求商品信息失败');
					})
					.finally(() => {
						this.loading = false;
					});
			},
			
			// 处理配置数据，分离颜色和容量
			processConfigData() {
			        const colors = new Map();
			        const storages = new Map();
			        
			        this.productConfigs.forEach(config => {
			            // 处理颜色
			            if (config.colorId && config.colorName) {
			                if (!colors.has(config.colorId)) {
			                    colors.set(config.colorId, {
			                        colorId: config.colorId,
			                        colorName: config.colorName
			                    });
			                }
			            }
					
					 // 处理容量
					            if (config.capacityId && config.capacityValue) {
					                if (!storages.has(config.capacityId)) {
					                    storages.set(config.capacityId, {
					                        capacityId: config.capacityId,
					                        capacityValue: config.capacityValue
					                    });
					                }
					            }
					        });
				
				this.availableColors = Array.from(colors.values());
				this.availableStorages = Array.from(storages.values());
				
			    // 默认选中第一个颜色和容量
			        if (this.availableColors.length > 0) {
			            this.selectedColor = this.availableColors[0].colorId;
			        }
			        if (this.availableStorages.length > 0) {
			            this.selectedStorage = this.availableStorages[0].capacityId;
			        }
			        
			        // 默认选中后立即获取组合价格
			        if (this.selectedColor && this.selectedStorage) {
			            this.fetchProductCombination();
			        }
			    },
			
			// 计数
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
					
				}
			},
			increaseQuantity() {
				this.quantity++;
				
			},
			
			// 商品属性方法
		handleSelect(type, value) {
		    switch (type) {
		        case 'color':
		            this.selectedColor = value;
		            break;
		        case 'storage':
		            this.selectedStorage = value;
		            break;
		        case 'package':
		            this.selectedPackage = value;
		            break;
		        default:
		            break;
		    }
		    
		    // 当颜色和容量都选中时，获取商品组合信息
		    if (this.selectedColor && this.selectedStorage) {
		        this.fetchProductCombination();
		    }
		},
		
		// 获取商品组合信息的方法
		    fetchProductCombination() {
		        if (!this.productIds) return;
		        
		        request.get(`/order/${this.productIds}`, {
		            params: {
		                colorId: this.selectedColor,
		                capacityId: this.selectedStorage
		            }
		        }).then(res => {
		            if(res.code === '200') {
		                // 存储单个商品的价格
		                this.combinationPrice = res.data.price;
		                this.combinationId = res.data.groupid;
		                this.currentCombination = {
		                    colorName: res.data.colorName,
		                    capacityValue: res.data.capacityValue
		                };
		            }else{
						this.$message({
							message: res.msg || '商品组合失败',
							type: 'error'
						})
					}
		        })
		    },
			// 加入购物车
			incar() {
			  if (!this.selectedColor || !this.selectedStorage) {
			    this.$message.warning('请选择商品规格')
			    return
			  }
			  // 创建加入购物车的数据
			  const productToAdd = {
			    id: this.product.product_id,
			    name: this.product.name,
			    image: this.product.image,
			    price: this.combinationPrice || this.product.price,
			    colorId: this.selectedColor,
			    colorName: this.currentCombination?.colorName || this.availableColors.find(c => c.colorId === this.selectedColor).colorName,
			    capacityId: this.selectedStorage,
			    capacityValue: this.currentCombination?.capacityValue || this.availableStorages.find(s => s.capacityId === this.selectedStorage).capacityValue,
			    quantity: this.quantity,
			    groupid: this.combinationId
			  }
			  console.log("加入购物车的数据：",productToAdd);
			  this.$store.commit('addToCart', productToAdd)
			  this.showAddSuccess = true
			  
			  // 3秒后自动隐藏成功提示
			  setTimeout(() => {
			    this.showAddSuccess = false
			  }, 3000)
			},
			
			// 立即购买
			buy() {
			  this.incar() // 先加入购物车
			  this.$router.push('/cart') // 跳转到购物车页面
			}
		
			

	
		}
	}
</script>
<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.loading {
  padding: 40px 0;
}

.product-content {
  display: flex;
  margin-top: 20px;
  gap: 40px;
}

.product-images {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.product-images img {
  width: 100%;
  height: auto;
  display: block;
}

.product-info {
  flex: 1;
  padding: 20px;
}

.product-name {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.product-price {
  font-size: 28px;
  color: #ff6700;
  font-weight: bold;
  margin-bottom: 20px;
}

.product-info p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  line-height: 1.6;
}

.config-section {
  margin-bottom: 25px;
}

.section-title {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
  font-weight: 500;
}

.config-item {
  display: inline-block;
  padding: 8px 15px;
  margin-right: 10px;
  margin-bottom: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.config-item:hover {
  border-color: #ff6700;
}

.config-item.active {
  border-color: #ff6700;
  background-color: #fff5f0;
  color: #ff6700;
}

.config-text {
  font-size: 14px;
}

.inventory-container {
  display: flex;
  align-items: center;
  margin: 25px 0;
}

.quantity-section {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  background: #f5f5f5;
  border: 1px solid #e0e0e0;
  font-size: 16px;
  cursor: pointer;
  outline: none;
}

.quantity-btn:hover {
  background: #eee;
}

.quantity-text {
  width: 40px;
  text-align: center;
  font-size: 14px;
}

.stock-status {
  color: #ff6700;
  font-size: 14px;
}

.carboxbutton {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.buyingoods, .buygoods {
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.buyingoods {
  background: #ff6700;
  color: white;
  border: 1px solid #ff6700;
}

.buyingoods:hover {
  background: #ff8333;
  border-color: #ff8333;
}

.buygoods {
  background: #f5f5f5;
  color: #ff6700;
  border: 1px solid #ff6700;
}

.buygoods:hover {
  background: #fff5f0;
}

.add-success-message {
  margin-top: 15px;
  padding: 10px;
  background: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.add-success-message i {
  margin-right: 5px;
  font-size: 16px;
}

.not-found {
  padding: 100px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .product-content {
    flex-direction: column;
  }
  
  .product-images, .product-info {
    flex: none;
    width: 100%;
  }
}
</style>
